#!/usr/bin/python
# -*- coding: cp1250 -*-

import psycopg2
  
class Connect:
    ''' read postgresql query output as iterator
    '''
    def __init__(self, con):
        #try:
        if con == '':
            self.con = psycopg2.connect("dbname='work' user='postgres' host='127.0.0.1' password=''") # create connection
        else:
            self.con = psycopg2.connect(con) # create connection
        #except:
        #    print "I am unable to connect to the database"
        self.cur = self.con.cursor()

class Query(Connect):
    ''' '''
    def __init__(self, q, con=''):
        Connect.__init__(self, con)
        self.sql = q
        self.cur.execute(q)

    def __getitem__(self, index):
        row = ''
        while row <> None:
            row = self.cur.fetchone() # cur.fetchall() or cur.fetchone()
            if row <> None: 
                return row
            else:
                raise IndexError

if __name__ == "__main__":
    ''' '''
    #c = "dbname='work' user='postgres' host='127.0.0.1' password=''"
    c = ''
    q = """select * from t002filea where c001 in ('0000000002', '0020000000','0010045000','0010405000')"""
    for row in Query(q, c):
        print row[0], row[1]
    q = """select * from t002filea where c001 in ('0000001002', '0010001000','0010045100','0010405100')"""
    for row in Query(q, c):
        print row[0], row[1]







